package cn.sc.collection;

import cn.sc.AbstractSimpleCache;
import cn.sc.collection.base.CacheObject;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName LocalSimpleCache
 * @Author 谢卓才
 * @Description 本地存储方式
 * @Date 2022/11/13 9:17
 */
public class LocalSimpleCache<V> extends AbstractSimpleCache<V> {
    public LocalSimpleCache(){}

    /**
     * 缓存池 缓存数据的地方
     */
    protected final Map<String,CacheObject<V>> cachePool = new ConcurrentHashMap<>();

    @Override
    public List<CacheObject<V>> valueAll() {
        return new ArrayList<>(cachePool.values());
    }
    @Override
    public CacheObject<V> value(String key) {
        CacheObject<V> node = cachePool.get(key);
        return node == null ? createNode(null,0) : node;
    }

    @Override
    public CacheObject<V> increase(String key, CacheObject<V> value) {
        CacheObject<V> result = cachePool.put(key, value);
        return result == null ? createNode(null,0) : result;
    }

    @Override
    public void increase(Map<String, CacheObject<V>> values) {
        cachePool.putAll(values);
    }

    @Override
    public Long cacheClear() {
        Set<String> keys = protoKeys();
        delete(keys);
        cachePool.clear();
        return Long.valueOf(keys.size());
    }

    @Override
    public Long delete(String key) {
        CacheObject<V> remove = cachePool.remove(key);
        if(remove != null){
            return 1L;
        }
        return 0L;
    }

    @Override
    public Long delete(Set<String> keys) {
        Long count = 0L;
        for (String key : keys) {
            count+=delete(key);
        }
        return count;
    }


    @Override
    public void addCache(Map<String,V> come){
        come.forEach((k,v) -> {
            increase(k,createNode(v,0));
        });
    }

    @Override
    public Set<String> protoKeys(){
        return cachePool.keySet();
    }

    @Override
    public boolean isEmpty() {
        return cachePool.isEmpty();
    }

    @Override
    public Long size(){
        return new Long(cachePool.size());
    }

}
